import Icon from '@/components/Icon';
import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import { baseURL } from '@/utils/request';
import { getAuth } from '@/utils/storage';
import classNames from 'classnames';
import { useEffect, useRef, useState } from 'react';
import { io, Socket } from 'socket.io-client';
import styles from './index.module.scss';

type MsgType = {
  msg: string;
  timestamp: number;
  type: 'robot' | 'user';
};

export default function Chat() {
  const [msgList, setMsgList] = useState([] as MsgType[]);

  const clientRef = useRef<Socket | null>(null);

  useEffect(() => {
    clientRef.current = io(baseURL, {
      query: {
        token: getAuth().token,
      },
      transports: ['websocket'],
    });

    clientRef.current.on('connect', () => {
      setMsgList([{ msg: '欢迎来到黑马，很高兴为您服务', timestamp: Date.now(), type: 'robot' }]);
    });

    clientRef.current.on('message', (data) => {
      setMsgList((preMsgList) => {
        return [...preMsgList, { ...data, type: 'robot' }];
      });
    });

    return () => {
      clientRef.current?.close();
    };
  }, []);

  useEffect(() => {
    window.scrollTo({
      top: document.body.scrollHeight,
      behavior: 'smooth',
    });
  }, [msgList]);

  const [userMsg, setUserMsg] = useState('');
  const handleSendMsg = () => {
    clientRef.current?.emit('message', { msg: userMsg, timestamp: Date.now() });
    setMsgList([...msgList, { msg: userMsg, timestamp: Date.now(), type: 'user' }]);
    setUserMsg('');
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleSendMsg();
    }
  };

  return (
    <div className={styles.root}>
      <NavBar fixed>小智同学</NavBar>

      <div className="chat-list">
        {msgList.map((item) => (
          <div
            key={item.timestamp}
            className={classNames('chat-item', { user: item.type === 'user' })}
          >
            {item.type === 'robot' ? (
              <Icon type="iconbtn_xiaozhitongxue" />
            ) : (
              <img src={'http://toutiao.itheima.net/images/user_head.jpg'} alt="" />
            )}

            <div className="message">{item.msg}</div>
          </div>
        ))}
      </div>

      <div className="footer">
        <div className="input-footer">
          <Input
            className="no-border"
            placeholder="请描述您的问题"
            value={userMsg}
            onChange={(e) => setUserMsg(e.target.value)}
            onKeyDown={handleKeyDown}
          />
          <Icon type="iconbianji" />
          <span className="send" onClick={handleSendMsg}>
            发送
          </span>
        </div>
      </div>
    </div>
  );
}
